package com.example.lj.uav.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lj.uav.MyApplication;
import com.example.lj.uav.R;
import com.example.lj.uav.adapter.RouteAdapter;
import com.example.lj.uav.bean.RouteLine;
import com.example.lj.uav.bean.RoutePoint;
import com.example.lj.uav.dao.MyDBDao;
import com.example.lj.uav.utils.CEComplexComparator;
import com.example.lj.uav.utils.ComparatorUtils;
import com.example.lj.uav.utils.ImageFileUtils;
import com.example.lj.uav.utils.KmlUtils;
import com.example.lj.uav.utils.TimeUtils;
import com.example.lj.uav.view.RouteMenuActivity;
import com.example.lj.uav.view.RouteSettingActivity;
import com.github.stuxuhai.jpinyin.PinyinException;
import com.github.stuxuhai.jpinyin.PinyinHelper;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FragmentRouteMenuLine extends Fragment implements View.OnClickListener, Handler.Callback {
    private LinearLayout mLlCreate;
    private LinearLayout mLlImport;
    private RecyclerView mRev;
    private int CREATE_NEW_ROUTE = 0;
    private int IMPORT_EXIST_ROUTE = 1;
    private final int CREATE_ROUTE = 0;
    private final int CREATE_AREA = 1;
    private MyDBDao dao;
    private RouteAdapter adapter;
    private Handler handler;
    private RouteMenuActivity mActivity;
    private List<RouteLine> lineList = new ArrayList<>();
    private RelativeLayout ll;
    private TextView tv;
    //    public RelativeLayout mRlMenu;
    private List<String> fileNames;
    private int flag;
    public int selectedQty = 0;
    private RouteAdapter searchAdapter;
    private List<RouteLine> searchList;
    private String mainPath;
    private String routeType;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_route, container, false);
        mLlCreate = view.findViewById(R.id.ll_route_menu_create);
        mLlImport = view.findViewById(R.id.ll_route_menu_import);
        mRev = view.findViewById(R.id.rev_route_list);
        ll = view.findViewById(R.id.rl_route_contain);
        tv = view.findViewById(R.id.tv);
//        mRlMenu = view.findViewById(R.id.rl_route_menu_second);
        fileNames = new ArrayList<>();
        searchList = new ArrayList<>();
        dao = MyApplication.dao;
        handler = new Handler(this);
        mActivity = (RouteMenuActivity) getActivity();
//        view.findViewById(R.id.ll_route_menu_second_1).setOnClickListener(this);
//        view.findViewById(R.id.ll_route_menu_second_2).setOnClickListener(this);
        initView();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        getLineData();
    }

    public void getLineData() {
        List<RouteLine> lines = dao.queryRoute();
        if (lines == null || lines.size() == 0) {
            mRev.setVisibility(View.GONE);
            ll.setVisibility(View.VISIBLE);
            tv.setVisibility(View.VISIBLE);
            mActivity.upDateSelectButton(false);
            return;
        }
        fileNames.clear();
        if (adapter == null) {//
            lineList.clear();
            lineList.add(new RouteLine());
            lineList.addAll(lines);
//            fileNames.add("");
            for (int i = 0; i < lineList.size(); i++) {
                fileNames.add(lineList.get(i).getFileName());
            }
            adapter = new RouteAdapter(lineList, handler);
            mRev.setAdapter(adapter);
            mRev.setVisibility(View.VISIBLE);
            ll.setVisibility(View.GONE);
            tv.setVisibility(View.GONE);
        } else {
            if (adapter.headerShow) {
                lineList.clear();
                lineList.add(new RouteLine(""));
                lineList.addAll(lines);
//                fileNames.add("");
                for (int i = 0; i < lineList.size(); i++) {
                    fileNames.add(lineList.get(i).getFileName());
                }
            } else {
                lineList.clear();
                lineList.addAll(lines);
                for (int i = 0; i < lineList.size(); i++) {
                    fileNames.add(lineList.get(i).getFileName());
                }
            }
            Collections.sort(lineList, new TimeUtils());
            adapter.notifyDataSetChanged();
        }
        mActivity.upDateSelectButton(true);
        mActivity.updateButtonStatus(lineList.size());
    }

    private void initView() {
        mLlImport.setOnClickListener(this);
        mLlCreate.setOnClickListener(this);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
        mRev.setLayoutManager(gridLayoutManager);
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.ll_route_menu_create:
                flag = CREATE_ROUTE;
//                mRlMenu.setVisibility(View.VISIBLE);
                intent = new Intent(getActivity(), RouteSettingActivity.class);
                intent.putExtra("names", (Serializable) fileNames);
                if (fileNames == null || fileNames.size() == 0) {
                    intent.putExtra("name", "新建航点飞行");
                } else {
                    intent.putExtra("name", "新建航点飞行" + (fileNames.size() - 1));
                }
                intent.putExtra("start_flag", 0);//是新建还是打开原有的
                startActivity(intent);
                break;
            case R.id.ll_route_menu_import:
                flag = IMPORT_EXIST_ROUTE;
//                mRlMenu.setVisibility(View.VISIBLE);
                mActivity.showStorageSelectDialog(true);
                break;
//            case R.id.ll_route_menu_second_1:
//                routeType = "WayLine";
//                if (flag==CREATE_ROUTE){
//
//                    mRlMenu.setVisibility(View.GONE);
//                }else{
//                    //显示dialog
//
//                }
//                break;
//            case R.id.ll_route_menu_second_2:
//                routeType = "WayArea";
//                if (flag==CREATE_ROUTE){
//                    intent = new Intent(getActivity(),RouteAreaSettingActivity.class);
//                    intent.putExtra("names", (Serializable) fileNames);
//                    if (fileNames==null||fileNames.size()==0){
//                        intent.putExtra("name", "新建建图航拍");
//                    }else{
//                        intent.putExtra("name", "新建建图航拍"+(fileNames.size()-1));
//                    }
//                    intent.putExtra("start_flag",0);
//                    startActivity(intent);
//                    mRlMenu.setVisibility(View.GONE);
//                }else{
//                    //显示dialog
//                    mActivity.showStorageSelectDialog(true);
//                }
//                break;
        }
    }

    @Override
    public boolean handleMessage(Message message) {
        switch (message.what) {
            case RouteAdapter.ROUTE_SELECTED:
                int position = message.arg1;
                RouteLine line = lineList.get(position);
                List<String> namesNew = new ArrayList<>();
                namesNew.addAll(fileNames);
                namesNew.set(position, "");
                Intent intent = new Intent(getActivity(), RouteSettingActivity.class);
                intent.putExtra("line", line);
                intent.putExtra("names", (Serializable) namesNew);
                intent.putExtra("start_flag", 1);
                intent.putExtra("name", line.getFileName());
                startActivity(intent);
                break;
            case RouteAdapter.CREATE_SELECTED:
//                Intent intentStart = new Intent(getActivity(),RouteSettingActivity.class);
//                intentStart.putExtra("names", fileNames);
//                intentStart.putExtra("name", "新建航线"+fileNames.length);
//                intentStart.putExtra("start_flag",1);
//                startActivity(intentStart);
                flag = CREATE_ROUTE;
                intent = new Intent(getActivity(), RouteSettingActivity.class);
                intent.putExtra("names", (Serializable) fileNames);
                if (fileNames == null || fileNames.size() == 0) {
                    intent.putExtra("name", "新建航点飞行");
                } else {
                    intent.putExtra("name", "新建航点飞行" + (fileNames.size() - 1));
                }
                intent.putExtra("start_flag", 0);//是新建还是打开原有的
                startActivity(intent);
//                mRlMenu.setVisibility(View.VISIBLE);
                break;
            case RouteAdapter.IMPORT_SELECTED:
                flag = IMPORT_EXIST_ROUTE;
//                mRlMenu.setVisibility(View.VISIBLE);
                mActivity.showStorageSelectDialog(true);
//                mActivity.showStorageSelectDialog(true);
                break;
            case RouteAdapter.ROUTE_CHECKED:
                selectedQty++;
                mActivity.mTvSelected.setText("已选" + selectedQty + "条");
                break;
            case RouteAdapter.ROUTE_CHECKED_CANCEL:
                selectedQty--;
                mActivity.mTvSelected.setText("已选" + selectedQty + "条");
                break;

        }
        return false;
    }


    public void selectButtonPressed() {
        adapter.headerShow = false;
        if (lineList.size() > 0)
            lineList.remove(0);
        adapter.notifyDataSetChanged();
        mActivity.mTvSelected.setText("已选" + selectedQty + "条");
    }

    public void completeButtonPressed() {
        adapter.headerShow = true;
//        List<RouteLine> list = new ArrayList<>();
//        list.add(new RouteLine());
//        list.addAll(lineList);
//        lineList.clear();
//        lineList.addAll(list);
//        adapter.notifyDataSetChanged();
        selectedQty = 0;
        mActivity.mTvSelected.setText("已选" + selectedQty + "条");
        getLineData();
    }

    public void deleteButtonPressed() {
        List<RouteLine> list = new ArrayList<>();
        List<RouteLine> deleteList = new ArrayList<>();
        for (int i = 0; i < lineList.size(); i++) {
            if (!lineList.get(i).isChecked()) {
                list.add(lineList.get(i));
            } else {
                deleteList.add(lineList.get(i));
            }
        }
        lineList.clear();
        lineList.addAll(list);
        for (int i = 0; i < deleteList.size(); i++) {
            dao.deleteRoute(deleteList.get(i).getFileName());
            ImageFileUtils.deleteImageFile(deleteList.get(i).getImagePath());
        }
        selectedQty = 0;
        mActivity.mTvSelected.setText("已选" + selectedQty + "条");
        adapter.notifyDataSetChanged();
    }

    public void collectButtonPressed() {
        for (int i = 0; i < lineList.size(); i++) {
            if (lineList.get(i).isChecked()) {
                if (lineList.get(i).getCollected() == 0) {
                    lineList.get(i).setCollected(1);
                } else {
                    lineList.get(i).setCollected(0);
                }
                dao.updateRoute(lineList.get(i), lineList.get(i).getFileName());
            }
        }
        getLineData();
        selectedQty = 0;
        mActivity.mTvSelected.setText("已选" + selectedQty + "条");
        mActivity.updateCollectList();
    }

    public void copyButtonPressed() {
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String time = format.format(new Date(System.currentTimeMillis()));
        for (int i = 0; i < lineList.size(); i++) {
            if (lineList.get(i).isChecked()) {
                RouteLine item = lineList.get(i);
                RouteLine copy = new RouteLine();
                String newFileName = item.getFileName() + "_副本";
                String v = newFileName.substring(newFileName.indexOf("_") + 1, newFileName.length());
                if (isFileNameRepeat(newFileName)) {
                    String regEx = "[^0-9]";
                    Pattern p = Pattern.compile(regEx);
                    Matcher m = p.matcher(v);
                    String ver = m.replaceAll(" ").trim();
                    if ("".endsWith(ver)) {
                        ver = "0";
                    }
                    int version = Integer.parseInt(ver) + 1;
                    newFileName = newFileName + version;
                }
                copy.setFileName(newFileName);
                copy.setAltitude(item.getAltitude());
                copy.setAltitudeMode(item.getAltitudeMode());
                copy.setUpdatePlace(item.getUpdatePlace());
                copy.setUpdateTime(System.currentTimeMillis());
                copy.setChecked(false);
                copy.setCollected(0);
                copy.setActionOnFinish(item.getActionOnFinish());
                copy.setCoordinates(item.getCoordinates());
                copy.setGimbalPitchMode(item.getGimbalPitchMode());
                copy.setHeadingMode(item.getHeadingMode());
                copy.setSpeed(item.getSpeed());
//                newLines.add(copy);
                dao.addRoute(copy);
                fileNames.add(copy.getFileName());
                List<RoutePoint> points = dao.queryPoints(item.getFileName());
                for (int j = 0; j < points.size(); j++) {
                    dao.addPoint(j, points.get(j), copy.getFileName());
                }
            }
        }
        selectedQty = 0;
        mActivity.mTvSelected.setText("已选" + selectedQty + "条");
        getLineData();
    }

    private boolean isFileNameRepeat(String newFileName) {
        for (int i = 0; i < fileNames.size(); i++) {
            if (newFileName.equals(fileNames.get(i))) {
                return true;
            }
        }
        return false;
    }

    public void onSearchMenuPressed() {
        searchList.clear();
        if (searchAdapter == null) {
            searchAdapter = new RouteAdapter(searchList, handler);
            searchAdapter.isSearching = true;
        }
        searchAdapter.headerShow = false;
        ll.setVisibility(View.GONE);
        mRev.setAdapter(searchAdapter);
    }

    public void onSearchButtonPressed(String fileName) {
        searchList.clear();
        Pattern pattern = Pattern.compile(fileName);
        for (int i = 1; i < lineList.size(); i++) {
            String name = lineList.get(i).getFileName();
            Matcher matcher = pattern.matcher(name);
            if (matcher.find()) {
                searchList.add(lineList.get(i));
            }
        }
        if (searchList.size() <= 0) {
            mActivity.searchNoData();
            mRev.setVisibility(View.GONE);
        } else {
            mActivity.searHasData();
            mRev.setVisibility(View.VISIBLE);
        }
        searchAdapter.notifyDataSetChanged();
    }

    public void onSearchCanceled() {
        searchList.clear();
        searchAdapter.notifyDataSetChanged();
        mRev.setAdapter(adapter);
        mRev.setVisibility(View.VISIBLE);
        if (lineList.size() == 0) {
            ll.setVisibility(View.VISIBLE);
        }
    }

    public void listByTime() {
        lineList.remove(0);
        Collections.sort(lineList, new TimeUtils());
        List<RouteLine> saveList = new ArrayList<>();
        saveList.addAll(lineList);
        lineList.clear();
        lineList.add(new RouteLine());
        lineList.addAll(saveList);
        adapter.notifyDataSetChanged();
    }

    public void listByName() {
        lineList.remove(0);
        //判断
        for (int i = 0; i < lineList.size(); i++) {
            String fileName = lineList.get(i).getFileName();
            String f = fileName.substring(0, 1);
            if (ComparatorUtils.containChinese(f)) {
                try {
                    String fpinyin = PinyinHelper.getShortPinyin(f);
                    int code = ComparatorUtils.SumStrAscii(fpinyin);
                    lineList.get(i).setFileNameCode(code);
                } catch (PinyinException e) {
                    e.printStackTrace();
                }
            } else if (ComparatorUtils.isEnglish(fileName)) {
                String first = fileName.substring(0, 1);
                int code = ComparatorUtils.SumStrAscii(first);
                lineList.get(i).setFileNameCode(code);
            } else {
                String first = fileName.substring(0, 1);
                int firstNo = Integer.parseInt(first);
                lineList.get(i).setFileNameCode(firstNo);
            }
        }
        Collections.sort(lineList, new CEComplexComparator());
        List<RouteLine> saveList = new ArrayList<>();
        saveList.addAll(lineList);
        lineList.clear();
        lineList.add(new RouteLine());
        lineList.addAll(saveList);
        adapter.notifyDataSetChanged();
    }

    public void showAllTypeRoute() {
        onSearchCanceled();
    }

    public void showAreaTypeRoute() {
        searchList.clear();
        searchList.add(new RouteLine());
        if (searchAdapter == null) {
            searchAdapter = new RouteAdapter(searchList, handler);
            searchAdapter.isSearching = true;
        }
        searchAdapter.headerShow = true;
        ll.setVisibility(View.GONE);
        mRev.setAdapter(searchAdapter);

        for (int i = 1; i < lineList.size(); i++) {
            if (lineList.get(i).getType().equals("area")) {
                searchList.add(lineList.get(i));
            }
        }
        searchAdapter.notifyDataSetChanged();
    }

    public void showLineTypeRoute() {
        searchList.clear();
        searchList.add(new RouteLine());
        if (searchAdapter == null) {
            searchAdapter = new RouteAdapter(searchList, handler);
            searchAdapter.isSearching = true;
        }
        searchAdapter.headerShow = true;
        ll.setVisibility(View.GONE);
        mRev.setAdapter(searchAdapter);

        for (int i = 1; i < lineList.size(); i++) {
            if (lineList.get(i).getType().equals("line")) {
                searchList.add(lineList.get(i));
            }
        }
        searchAdapter.notifyDataSetChanged();
    }

    public List<String> getFileNames() {
        return fileNames;
    }

    public void exportButtonPressed(String path) {
        for (RouteLine line : lineList) {
            if (line.isChecked()) {
                List<RoutePoint> points = dao.queryPoints(line.getFileName());
                KmlUtils.createKml(path, line, points);
            }
        }
        Toast.makeText(getContext(), "导出成功", Toast.LENGTH_LONG).show();
    }


//    public class TimeUtils implements Comparator<RouteLine> {
//        @Override
//        public int compare(RouteLine h1, RouteLine h2) {
//            if (h1.getUpdateTime() > h2.getUpdateTime()) {
//                return 1;
//            } else if (h1.getUpdateTime() == h2.getUpdateTime()) {
//                return 0;
//            } else {
//                return -1;
//            }
//        }
//    }

//    class CEComplexComparator implements Comparator<RouteLine> {
//        @Override
//        public int compare(RouteLine line, RouteLine line2) {
//            if (line.getFileNameCode() > line2.getFileNameCode()) {
//                return 1;
//            } else if (line.getFileNameCode() == line2.getFileNameCode()) {
//                return 0;
//            } else {
//                return -1;
//            }
//        }
//    }
}
